package My;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1",10086);
        System.out.println("服务器已经连接成功了");
        while (true) {
            System.out.println("欢迎来到本聊天室");
            System.out.println("1.登录  2.注册");
            System.out.print("请输入你的选择：");
            Scanner sc = new Scanner(System.in);
            String choose = sc.next();
            switch (choose){
                case "1"-> Login(socket);
                case "2"-> System.out.println("注册");
                default -> System.out.println("没有该选项");
            }
        }

    }
    public static void Login(Socket socket) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入用户名:");
        String username = sc.next();
        System.out.print("请输入密码:");
        String password = sc.next();

        StringBuilder sb = new StringBuilder();
        sb.append("username=").append(username).append("&password=").append(password);


        bw.write("login");
        bw.newLine();
        bw.flush();
        bw.write(sb.toString());
        bw.newLine();
        bw.flush();

        //接收数据
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String message = br.readLine();
        System.out.println(message);

        if ("1".equals(message)){
            System.out.println("登陆成功，开始聊天");
            new Thread(new ClientMyRunnable(socket)).start();
            talk2All(bw);
        }else if("2".equals(message)){
            System.out.println("密码输入错误");
        } else if ("3".equals(message)) {
            System.out.println("用户名不存在");
        }
    }
    public static void talk2All(BufferedWriter bw)throws IOException{
        Scanner sc = new Scanner(System.in);
        while (true){
            System.out.println("请输入你想说的话:");
            String str = sc.next();
            bw.write(str);
            bw.newLine();
            bw.flush();
        }
    }
}
class ClientMyRunnable implements Runnable{
    Socket socket;
    public ClientMyRunnable(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        while (true){
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String msg = br.readLine();
                System.out.println(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
